Python Lab: Systems of Equations
Contents
8.2. Python Lab: Systems of Equations#
Linear equation: If \(a\), \(b\), and \(c\) are real numbers, the graph of an equation of the form
\[\begin{align*}
ax+by = c
\end{align*}\]
is a straight line (if \(a\) and \(b\) are not both zero), so such an equation is called a linear equation in the variables \(x\) and \(y\).
Example: Solve
\[\begin{align*}
\begin{cases}
x+y=0\\
x-y=0,\\
\end{cases}
\end{align*}\]
Graphically.
matplotlib:
# numpy
import numpy as np
# matplotlib
import matplotlib.pyplot as plt
%matplotlib inline
plt.style.use('seaborn-white')
x = np.linspace( -10 , 10 ,100)
fig, ax = plt.subplots(nrows=1, ncols=1, figsize=(6, 6), sharex = False)
_ = ax.plot(x, -x, color='r', label='x + y = 0')
_ = ax.plot(x, x, color='b', label='x - y = 0')
_ = ax.set_xlabel('$x$', fontsize=18)
_ = ax.set_ylabel('$y$', fontsize=18)
_ = ax.legend(loc='best', bbox_to_anchor=(1.01, 0., 0.2, 0.6))
_ = ax.set_xlim([min(x),max(x)])
_ = ax.set_ylim([min(x),max(x)])
_ = ax.grid(True, which='both')
_ = ax.axhline(y=0, color='k')
_ = ax.axvline(x=0, color='k')
plotly:
## plotly
from plotly.offline import iplot
import plotly.graph_objs as go
x = np.linspace( -10 , 10 ,100)
fig = go.Figure()
fig.add_trace(go.Scatter(x= x, y= -x, line=dict(color='Blue', width= 1.5), name = 'x + y = 0'))
fig.add_trace(go.Scatter(x= x, y= x, line=dict(color='OrangeRed', width= 1.5), name = 'x - y = 0'))
# Update
fig.update_layout(plot_bgcolor= 'white', width = 600)
fig.update_xaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
showgrid=True, gridwidth=1, gridcolor='Lightgray',
zeroline=True, zerolinewidth=1.5, zerolinecolor='black')
fig.update_yaxes(showline=True, linewidth=1, linecolor='Lightgray', mirror=True,
showgrid=True, gridwidth=1, gridcolor='Lightgray',
zeroline=True, zerolinewidth=1.5, zerolinecolor='black')
fig.update_xaxes(title_text='x', range=[-10, 10])
fig.update_yaxes(title_text='y', range=[-10, 10])
fig.show()
Example: Solve
\[\begin{align*}
\begin{cases}
x+y+z=2\\
x+y+z=5
\end{cases}.
\end{align*}\]
matplotlib:
fig = plt.figure(figsize = (20, 10))
ax = fig.add_subplot(111, projection='3d')
# Make data.
X = np.linspace( -10 , 10 ,100)
Y = np.linspace( -10 , 10 ,100)
X, Y = np.meshgrid(X, Y)
Z1 = 2 - X - Y
Z2 = 5 - X - Y
# Plot the surface.
surf = ax.plot_surface(X, Y, Z1, color = 'blue', linewidth=0, antialiased=False)
_ = ax.plot_surface(X, Y, Z2, color = 'lightgreen', linewidth=0, antialiased=False)
_ = ax.set_zlim(-20, 40)
# _ = ax.zaxis.set_major_locator(LinearLocator(10))
_ = ax.set_xlabel('x', fontsize=18)
_ = ax.set_ylabel('y', fontsize=18)
_ = ax.set_zlabel('z', fontsize=18)
plotly:
X = np.linspace( -10 , 10 ,100)
Y = np.linspace( -10 , 10 ,100)
X, Y = np.meshgrid(X, Y)
Z1 = 2 - X - Y
Z2 = 5 - X - Y
fig = go.Figure()
fig.add_trace(go.Surface(z=Z1, x=X, y=Y, colorscale='Greens', colorbar_len=0.5))
fig.add_trace(go.Surface(z=Z2, x=X, y=Y, colorscale='Blues', colorbar_len=0.5))
fig.update_layout(scene = dict(xaxis = dict(tickvals= list(np.arange(-10,11,5))),
yaxis = dict(tickvals= list(np.arange(-10,11,5))),
zaxis = dict(nticks=5, ticks='outside',tick0=0, tickwidth=4),),
margin=dict(r=10, l=10, b=10, t=10))
fig.show()
8.2.1. Solving linear system using back-substitution#
Example: Solve the following linear system using back-substitution.
\[\begin{equation*}
\begin{cases}
x_{1}+2\,x_{2}+3\,x_{3}=2\\
4\,x_{1}-3\,x_{2}+x_{3}=-3\\
x_{2}-2\,x_{1}+3\,x_{3}=5
\end{cases}
\end{equation*}\]
The corresponding augmented matrix is
from __future__ import division
from sympy import init_session, init_printing, Matrix
init_printing(use_unicode=True)
M = Matrix([[1 , 2 , 3 , 2], [4 , -3 , 1 , -3], [-2 , 1 , 3 , 5]])
M
In RREF:
RREF= M.rref()[0]
RREF
Therefore, the solutions are:
from IPython.display import display
display(r'x_1 = %i, x_2 = %i and x_3 = %i' % (RREF[0,-1], RREF[1,-1], RREF[2,-1]))
'x_1 = -1, x_2 = 0 and x_3 = 1'
To verify our answer, we can use linalg from Numpy. This requires converting the Matrix M into an array.
A = np.asarray(M[:,:-1], dtype = int)
B = np.asarray(M[:,-1], dtype = int)
Matrix(np.linalg.solve(A, B))